package com.gitee.limaozhi.socket.lesson03.example4;

import com.gitee.limaozhi.socket.lesson03.example3.Handler;
import com.gitee.limaozhi.socket.lesson03.example3.HandlerAdapter;

import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * HTTP服务器业务处理器
 *
 * @author hzlimaozhi
 * @date 2019/08/07 11:30
 */
public class HttpServerHandler extends HandlerAdapter {

    private int prevReq = -1;
    private AtomicInteger req = new AtomicInteger(0);
    private boolean fireFinish = false;

    @Override
    public Handler handle(Object object) {
        context().execute(() -> {
            HttpRequest request = (HttpRequest) object;
            context().print(context().getName() + "：收到：" + request);

            String uri = request.getUri();
            String body;
            if (uri.contains("/hello")) {
                body = "你好";
            } else if (uri.contains("/weather")) {
                body = "晴天";
            } else if (uri.contains("/time")) {
                body = new Date().toString();
            } else if (uri.contains("/temperature")) {
                body = "36度";
            } else if (uri.contains("/bye")) {
                body = "拜拜";
            } else {
                body = "说人话";
            }

            HttpResponse response = new HttpResponse();
            response.setKeepAlive(request.isKeepAlive());
    //        response.setKeepAlive(false);
            response.setContent("<html><title>HTTP服务器</title><body>" + body + "</body></html>");

            next().handle(response);
            req.incrementAndGet();
            fireFinish();
        });
        return this;
    }

    @Override
    public Handler finish(int prevReq) {
        this.prevReq = prevReq;
        fireFinish();
        return this;
    }

    private synchronized void fireFinish() {
        if (!fireFinish) {
            if (prevReq == req.get()) {
                fireFinish = true;
//                context().print(context().getName() + "：HttpServer：" + req.get());
                next().finish(req.get());
            }
        }
    }

}
